<script setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { getEnterpriseListApi } from '@/api/user'
import { getEnterpriseJobListApi } from '@/api/baseData'
import { useUserStore } from '@/stores/user'
import { applyJobApi, isApplyJobApi } from '@/api/job'
import { dayFormat } from '@/utils/common/dayjs'
import { showStatusMessage } from '@/utils/common/showMessage'
import FormJob from '@/components/Job/form.vue'
import { useRouter } from 'vue-router'
const loading = ref(false)
const userStore = useUserStore()
// 地图实例
const map = ref(null)
const AMap = ref(null)
const zoom = ref(6.5)
// 地图工具
const mapTools = ref({
  Scale: null,
  ToolBar: null,
  ControlBar: null,
  MapType: null
})

function initMap() {
  loading.value = true
  window._AMapSecurityConfig = {
    securityJsCode: '42abe75c534a35e6f01fe2ecc86c6ade'
  }
  AMapLoader.load({
    key: 'e817a26a6ac8d82d6b6436308af376d3', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.Scale',
      'AMap.Geolocation',
      'AMap.Autocomplete',
      'AMap.PlaceSearch',
      'AMap.ToolBar',
      'AMap.AutoComplete',
      'AMap.ControlBar',
      'AMap.MapType'
    ] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((amap) => {
      AMap.value = amap
      map.value = new AMap.value.Map('map', {
        // 设置地图容器id
        viewMode: '3D', // 是否为3D地图模式
        zoom: zoom.value, // 初始化地图级别
        center: [116.397428, 39.90923], // 初始化地图中心点位置
        zooms: [3, 17]
      })
      // 确保地图初始化完成后再添加插件
      addAMapPlugin()
      addLabelsLayer()
      onMapEvent()
      loading.value = false
    })
    .catch((e) => {
      console.log(e)
      loading.value = false
    })
}

function addAMapPlugin() {
  if (!AMap.value || !map.value) return

  let Geolocation = new AMap.value.Geolocation({
    enableHighAccuracy: true, //是否使用高精度定位，默认:true
    timeout: 10000, //超过10秒后停止定位，默认：5s
    position: 'RB', //定位按钮的停靠位置
    buttonOffset: new AMap.value.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
    zoomToAccuracy: true //定位成功后是否自动
  })
  map.value.addControl(Geolocation)
  // 修改 Autocomplete 的初始化方式
  const autoOptions = {
    input: 'tipinput',
    city: '全国'
  }
  const autoComplete = new AMap.value.Autocomplete(autoOptions)
  const placeSearch = new AMap.value.PlaceSearch({
    map: map.value
  })
  autoComplete.on('select', function (e) {
    console.log('选择', e)

    placeSearch.setCity(e.poi.adcode)
    placeSearch.search(e.poi.name)
  })
  placeSearch.on('markerClick', function (e) {
    console.log('点背点击', e.data)

    // map.value.setCenter(e.poi.location)
    // map.value.setZoom(18)
  })
  // 添加定位事件监听
  Geolocation.on('complete', (data) => {
    // data是具体的定位信息
    console.log('定位成功', data)
  })
  Geolocation.on('error', (data) => {
    // 定位出错
    console.error('定位失败', data)
  })

  // 开始定位
  Geolocation.getCurrentPosition()
  // 添加工具栏
  mapTools.value.ToolBar = new AMap.value.ToolBar({
    position: {
      top: '880px',
      right: '20px'
    }
  })
  mapTools.value.Scale = new AMap.value.Scale({
    position: 'LB'
  })
  mapTools.value.ControlBar = new AMap.value.ControlBar({
    showZoomBar: true,
    showControlButton: true,
    position: {
      top: '750px',
      right: '10px'
    }
  })
  // 切换地图图层
  mapTools.value.MapType = new AMap.value.MapType({
    defaultType: 0,
    showRoad: true,
    showTraffic: false
  })
  map.value.addControl(mapTools.value.ToolBar)
  map.value.addControl(mapTools.value.Scale)
  map.value.addControl(mapTools.value.ControlBar)
  map.value.addControl(mapTools.value.MapType)
}
function onMapEvent() {
  map.value.on('zoomend', (data) => {
    zoom.value = map.value.getZoom()
  })
}
const enterList = ref([])
// 获取所有企业列表
async function getEnterpriseList() {
  const res = await getEnterpriseListApi()
  enterList.value = res.data.filter((item) => {
    return item.position !== null
  })
}
getEnterpriseList()
// 当前选中的企业信息
const currentEnter = ref(null)
// 当前选中的企业职位列表
const currentEnterJobList = ref([])
const isShowCurrentEnter = ref(false)
// 添加标记
function addLabelsLayer() {
  if (!AMap.value || !map.value) return
  // 创建图层
  const labelsLayer = new AMap.value.LabelsLayer({
    zooms: [3, 17],
    zIndex: 1000,
    collision: true, //该层内标注是否避让
    allowCollision: true //不同标注层之间是否避让
  })
  const labelMarkerArray = []
  enterList.value.forEach((item) => {
    const positionArray = JSON.parse(item.position).map(Number)


    const icon = createIcon(item)
    const text = createText(item)
    //创建 LabelMarker
    const labelMarker = new AMap.value.LabelMarker({
      name: '标注', //此属性非绘制文字内容，仅为标识使用
      // [116.397428, 39.90923]
      position: positionArray,
      zIndex: 16,
      rank: 1, //避让优先级
      icon: icon, //标注图标，将 icon 对象传给 icon 属性
      text: text //标注文本，将 text 对象传给 text 属性
    })
    labelMarker.on('click', async (e) => {
      console.log('点击', item)
      currentEnter.value = item
     map.value.setCenter(positionArray,true,300)
 
      const res = await getEnterpriseJobListApi({ account: item.account })
      currentEnterJobList.value = res.data
     
      isShowCurrentEnter.value = true
    })
    //添加一个 labelMarker
    labelMarkerArray.push(labelMarker)
  })

  labelsLayer.add(labelMarkerArray)

  // 将图层添加到地图上
  map.value.add(labelsLayer)
}
function createText(item) {
  //设置文字对象
  const text = {
    content: item.enterpriseName, //要展示的文字内容
    direction: 'right', //文字方向，有 icon 时为围绕文字的方向，没有 icon 时，则为相对 position 的位置
    offset: [-30, -30], //在 direction 基础上的偏移量
    //文字样式
    style: {
      fontSize: 12, //字体大小
      fillColor: '#000', //字体颜色
      strokeColor: '#fff', //描边颜色
      strokeWidth: 3 //描边宽度
    }
  }
  return text
}
function createIcon(item) {
  //设置一个图标对象
  const icon = {
    type: 'image', //图标类型，现阶段只支持 image 类型
    image: 'http://127.0.0.1:3007/upload/企业图标.png', //可访问的图片 URL
    size: [30, 30], //图片尺寸
    anchor: 'center' //图片相对 position 的锚点，默认为 bottom-center
  }
  return icon
}

// 格式化地址数据
function formatAddress(address) {
  try {
    if (typeof address === 'string') {
      const parsed = JSON.parse(address)
      if (Array.isArray(parsed)) {
        return parsed.join('')
      }
    }
    return address || ''
  } catch (e) {
    console.warn('地址解析错误:', e)
    return address || ''
  }
}
const formJobRef = ref(null)
// 申请职位
const dialogTableVisible = ref(false)
const FormJobData = ref({
  enterpriseName: '',
  jobName: '',
  phone: '',
  applyTime: dayFormat(new Date()),
  // 简历
  resume: '',
  // 专业
  major: userStore.userInfo.major || '',
  name: userStore.userInfo.name || ''
})
const applyDataInfo = ref({
  // 企业账号
  exterpriseAccount: '',
  // 企业名称
  enterpriseName: '',
  // 职位名称
  jobName: '',
  // 学生账号
  studentAccount: '',
  // 学生姓名
  name: '',
  // 专业
  major: '',
  // 个人练习电话
  phone: '',
  // 申请时间
  applyTime: '',
  // 简历
  resume: '',
  jobId: '',
  salary: ''

})
const formJobOpt = [
  {
    prop: 'enterpriseName',
    label: '企业名称',
    type: 'input',
    disabled: true
  },
  {
    prop: 'jobName',
    label: '职位名称',
    type: 'input',
    disabled: true
  },
  {
    prop: 'name',
    label: '姓名',
    type: 'input',
    disabled: true
  },
  {
    prop: 'major',
    label: '专业',
    type: 'input',
    disabled: true
  },
  {
    prop: 'phone',
    label: '个人联系电话',
    type: 'input',
  },
  {
    prop: 'applyTime',
    label: '申请时间',
    type: 'input',
    disabled: true
  },
  {
    prop: 'resume',
    label: '上传简历',
    type: 'uploadResume',
  },

]
const btnJobOpt = [
  {
    name: '取消',
    btnType: 'info',
    prop: 'cancel'
  },
  {
    name: '提交',
    btnType: 'primary',
    prop: 'submit'
  }
]
//dialog关闭前的回调
function handleDialogClose() {
  formJobRef.value.reset()
}
// 详情
async function handletTableApply(data) {
  console.log(data)

  // 判断是否已经申请过职位
  const res = await isApplyJobApi({
    studentAccount: userStore.userInfo.account,
    jobName: data.jobName,
    exterpriseAccount: data.account
  })
  if (res.status == 1) {
    showStatusMessage(res)
    return
  }
  //申请面试
  dialogTableVisible.value = true
  applyDataInfo.value.exterpriseAccount = data.account
  applyDataInfo.value.jobId = data.id
  applyDataInfo.value.salary = data.salary
  FormJobData.value.jobName = data.jobName
  FormJobData.value.enterpriseName = data.enterpriseName
}
onMounted(() => {
  initMap()
})
function handleForm(type, data) {
  // console.log(type, data)
  switch (type) {
    case 'query':
      query(data)
      break
    case 'add':
      addForm()
      break
    case 'output':
      exportToExcel()
      break
    case 'reset':
      reset(data)
      break
    case 'import':
      handleUpload(data)
      break
    case 'submit':
      handleSubmit(data)
      break
    case 'cancel':
      handleCancel(data)
      break
    default:
      break
  }
}
function handleCancel(data){
  dialogTableVisible.value = false
}
// 点击提交申请
async function handleSubmit(data) {
  applyDataInfo.value.studentAccount = userStore.userInfo.account
  applyDataInfo.value.enterpriseName = data.enterpriseName
  applyDataInfo.value.name = data.name
  applyDataInfo.value.phone = data.phone
  applyDataInfo.value.resume = data.resume
  applyDataInfo.value.applyTime = data.applyTime
  applyDataInfo.value.jobName = data.jobName
  applyDataInfo.value.major = data.major
  const res = await applyJobApi(applyDataInfo.value)
  showStatusMessage(res)
  dialogTableVisible.value = false
}
onUnmounted(() => {
  map.value?.destroy()
})
const router = useRouter()
function handleBack() {
  router.back()
}
</script>
<template>
  <div class="container">
    <div id="map" v-loading="loading"></div>
    <!-- 添加返回按钮 -->
    <div class="back-btn" @click="handleBack">
        <svg viewBox="0 0 1024 1024" width="20" height="20">
          <path
            d="M768 903.232l-50.432 56.768L256 512l461.568-448 50.432 56.768L364.928 512z"
            fill="currentColor"
          />
        </svg>
    </div>
    <div class="zoom">
      <text>当前缩放级别</text>
      {{ zoom }}
    </div>
    <div id="input">
      <input id="tipinput" type="text" placeholder="请输入地址关键字" class="search-input" />
    </div>
    <div class="job-detail" v-if="isShowCurrentEnter">
      <div class="enterprise-info">
        <div class="enterprise-header">
          <h2>{{ currentEnter.enterpriseName }}</h2>
          <div class="close-btn" @click="isShowCurrentEnter = false">×</div>
        </div>
        <div class="enterprise-content">
          <div class="info-item">
            <span class="label">公司地址：</span>
            <span class="value"
              >{{ formatAddress(currentEnter.enterpriseAddress)
              }}{{ currentEnter.detailAddress }}</span
            >
          </div>
          <div class="info-item">
            <span class="label">所属行业：</span>
            <span class="value">{{ currentEnter.industry }}</span>
          </div>
          <div class="info-item">
            <span class="label">公司简介：</span>
            <span class="value">{{ currentEnter.detail }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ currentEnter.phone }}</span>
          </div>
        </div>
      </div>
      <div class="job-list">
        <h3>招聘职位</h3>
        <div class="job-item" v-for="job in currentEnterJobList" :key="job.id">
          <div class="job-header">
            <span class="job-name">{{ job.jobName }}</span>
            <span class="job-salary">{{ job.salary }}</span>
          </div>
          <div class="job-content">
            <div class="job-info">
              <span class="label">工作地点：</span>
              <span class="value"
                >{{ formatAddress(job.jobLocation) }}{{ job.jobDetailLocation }}</span
              >
            </div>
            <div class="job-info">
              <span class="label">职位描述：</span>
              <span class="value">{{ job.jobDesc }}</span>
            </div>
            <div class="job-info">
              <span class="label">职位要求：</span>
              <span class="value">{{ job.jobRequire }}</span>
            </div>
            <div class="job-info">
              <span class="label">联系电话：</span>
              <span class="value">{{ job.phone }}</span>
            </div>
            <div class="job-info" style="justify-content: center">
              <el-button
                type="primary"
                v-if="userStore.userInfo.identity === '学生'"
                plain
                @click="handletTableApply(job)"
                >投递</el-button
              >
            </div>
          </div>
        </div>
        <div class="job-item" v-if="currentEnterJobList.length === 0">暂无招聘职位</div>
        
      </div>
    
    </div>
      <!-- 申请职位 -->
      <el-dialog
          v-model="dialogTableVisible"
          title="申请职位，填写资料"
          width="800"
          @close="handleDialogClose"
        >
          <FormJob
            ref="formJobRef"
            :data="FormJobData"
            :form-opt="formJobOpt"
            :btn-opt="btnJobOpt"
            @handleForm="handleForm"
          >
          </FormJob>
        </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  #map {
    width: 100vw;
    height: 100vh;
  }
  .back-btn {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 999;
    background-color: rgba(255, 255, 255, 0.9);
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    cursor: pointer;
    animation: float 3s ease-in-out infinite;

    &:hover {
      background-color: #fff;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
      transform: scale(1.05) translateY(-2px);

      svg {
        animation: bounce 0.5s ease;
      }
    }

    a {
      color: #333;
      text-decoration: none;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
    }

    svg {
      transition: transform 0.3s ease;
    }
  }
  .zoom {
    position: absolute;
    bottom: 50px;
    left: 20px;
    z-index: 999;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.98), rgba(255, 255, 255, 0.9));
    padding: 25px 35px;
    border-radius: 25px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
    border: 3px solid rgba(255, 255, 255, 0.4);
    animation: pulse 1.5s infinite;

    &:hover {
      transform: translateY(-5px) scale(1.1);
      box-shadow: 0 15px 50px rgba(0, 0, 0, 0.4);
    }

    text {
      font-size: 18px;
      color: #333;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 2px;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    span {
      font-size: 36px;
      font-weight: 900;
      background: linear-gradient(45deg, #2196f3, #00bcd4);
      -webkit-background-clip: text;
      background-clip: text;
      -webkit-text-fill-color: transparent;
      text-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: 0;
        width: 100%;
        height: 3px;
        background: linear-gradient(45deg, #2196f3, #00bcd4);
        border-radius: 2px;
      }
    }
  }

  @keyframes float {
    0%,
    100% {
      transform: translateY(0);
    }
    50% {
      transform: translateY(-5px);
    }
  }

  @keyframes bounce {
    0%,
    100% {
      transform: translateX(0);
    }
    25% {
      transform: translateX(-3px);
    }
    75% {
      transform: translateX(3px);
    }
  }

  @keyframes pulse {
    0% {
      box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
      transform: scale(1);
    }
    50% {
      box-shadow: 0 10px 40px rgba(33, 150, 243, 0.4);
      transform: scale(1.05);
    }
    100% {
      box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
      transform: scale(1);
    }
  }

  #input {
    position: absolute;
    top: 20px;
    right: 200px;
    z-index: 999;
    #tipinput {
      width: 300px;
      height: 50px;
      padding: 0 20px;
      border: none;
      border-radius: 25px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      font-size: large;
      transition: all 0.3s ease;
      background-color: rgba(255, 255, 255, 0.9);

      &:focus {
        outline: none;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
        background-color: #fff;
      }

      &::placeholder {
        color: #999;
      }
    }
  }
  :deep(.amap-ctrl-list-layer) {
    width: 150px;
    border-radius: 20px;
    font-size: 30px !important;
  }
  :deep(.auto-item) {
    font-size: large;
  }
  .job-detail {
    position: absolute;
    top: 45%;
    left: 1%;
    transform: translate(0%, -50%);
    width: 600px;
    max-height: 75vh;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    padding: 30px;
    z-index: 1000;
    overflow-y: auto;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);

    .enterprise-info {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);

      .enterprise-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h2 {
          margin: 0;
          color: #333;
          font-size: 24px;
        }

        .close-btn {
          font-size: 24px;
          cursor: pointer;
          color: #666;
          transition: color 0.3s;

          &:hover {
            color: #333;
          }
        }
      }

      .enterprise-content {
        .info-item {
          margin-bottom: 15px;
          display: flex;
          align-items: flex-start;

          .label {
            color: #666;
            width: 80px;
            flex-shrink: 0;
          }

          .value {
            color: #333;
            flex: 1;
            line-height: 1.5;
          }
        }
      }
    }

    .job-list {
      h3 {
        margin: 0 0 20px;
        color: #333;
        font-size: 20px;
      }

      .job-item {
        background: rgba(255, 255, 255, 0.8);
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        transition:
          transform 0.3s,
          box-shadow 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .job-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;

          .job-name {
            font-size: 18px;
            font-weight: bold;
            color: #333;
          }

          .job-salary {
            color: #ff6b6b;
            font-weight: bold;
          }
        }

        .job-content {
          .job-info {
            margin-bottom: 10px;
            display: flex;
            align-items: flex-start;

            .label {
              color: #666;
              width: 80px;
              flex-shrink: 0;
            }

            .value {
              text-align: left;
              color: #333;
              flex: 1;
              line-height: 1.5;
            }
          }
        }
      }
    }
  }
}
</style>
